package com.vrv.vap.uploader.controller;

import com.github.pagehelper.PageInfo;
import com.vrv.vap.uploader.model.FileDto;
import com.vrv.vap.uploader.service.FileListService;
import com.vrv.vap.uploader.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author wh1107066
 * @date 2021/9/29 19:30
 */
@Controller
@RequestMapping("/fileInfos")
@Api(value = "上传文件管理", tags = "上传文件管理模块")
public class UploadFileListController {

    private Logger logger = LoggerFactory.getLogger(UploadFileListController.class);

    @Autowired
    private FileListService fileListService;

    @Autowired
    private FileService fileService;


    @ApiOperation("文件删除")
    @CrossOrigin
    @ResponseBody
    @DeleteMapping("{id:[\\d]+}")
    public boolean delete(@PathVariable String id) {
        boolean update = false;
        FileDto fileDto = fileService.queryFileById(Long.valueOf(id));
//        if (fileDto != null) {
//            fileService.deleteById(fileDto.getId());
//            File file = new File(fileDto.getPath());
//            if (file.exists()) {
//                file.delete();
//            }
        //        }
        /**
         * 假删除
         */
        fileDto.setMd5(null);
        fileDto.setStatus(1);
        update = fileService.update(fileDto);

        return update;
    }

    @CrossOrigin
    @GetMapping
    @ResponseBody
    @ApiOperation("文件列表分页展示")
    public PageInfo<FileDto> findByPage(FileDto fileDto, @RequestParam(value = "page") int pageNum,
                                        @RequestParam(value = "size") int pageSize) {
        PageInfo<FileDto> pageInfo = fileListService.findByPageService(fileDto, pageNum, pageSize);
        return pageInfo;
    }

    @GetMapping(value = "/download/{id}")
    @CrossOrigin
    @ApiOperation("文件下载")
    public void findByPage(@PathVariable String id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        FileDto fileDto = fileService.queryFileById(Long.valueOf(id));
        Assert.notNull(fileDto, "获取的文件为空！");
        String path = fileDto.getPath();
        logger.info(path);
        OutputStream os = null;
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = fileDto.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 处理文件中文乱码问题
            String userAgent = request.getHeader("User-agent");
            byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8");
            String fileNameDisplay = new String(bytes, "ISO-8859-1");
            // 设置response的Header
            response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileNameDisplay));
            response.addHeader("Content-Length", "" + file.length());
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            os.write(buffer);
            os.flush();
        } catch (IOException ex) {
            logger.error("异常!", ex);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

}
